package coderead.tomcat;
/**
 * @Copyright 源码阅读网 http://coderead.cn
 */

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 用于测试连接数
 *
 * @author 鲁班大叔
 * @date 2021
 */
@WebServlet(name = "pingServlet",urlPatterns = "/ping2")
public class PingAction extends HttpServlet {
    private AtomicLong actives = new AtomicLong();
    public static PingAction instance;

    @Override
    public void init() throws ServletException {
        instance = this;
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
        handleResponse(req, resp);
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
        handleResponse(req, resp);
    }

    private void handleResponse(HttpServletRequest req, HttpServletResponse resp) {
        try {
            actives.incrementAndGet();
            if (req.getParameterMap().containsKey("sleep")) {
                Thread.sleep(Long.MAX_VALUE);
            }
            resp.getWriter().println("pong--");
        } catch (InterruptedException | IOException e) {
            e.printStackTrace();
        } finally {
            actives.decrementAndGet();
        }
    }

}
